<?php
class Admincpanel_Model_Group extends Zend_Db_Table
{
	protected $_name = 'user_group';
	protected $_primary = 'id';
	protected $_arrParam = array();
	protected $_db;
	
	public function __construct($arrParam = null)
	{
		$this->_filter = new Zend_Filter_StripTags();
		if ( ! empty($arrParam))
		{
			foreach ($arrParam as $key => $value)
			{
				if ( ! in_array($key, array('module', 'controller', 'action', 'task')))
				{
					$this->_arrParam[$key] = $this->_filter->filter($value);
				}
			}
			unset($arrParam);
		}
		$this->_db = Zend_Registry::get('connectDb');
	}
	
	public function createpres()
	{
		if ($this->_arrParam['groupname'] == '' OR $this->_arrParam['status'] == '')
		{
			return 'required';
		}
		
		if ($this->isExistAdd())
		{
			return 'exist';	
		}
		
		$row =  $this->fetchNew();
		$row->group_name 	= $this->_arrParam['groupname'];
		$row->status		= $this->_arrParam['status'];
						
		$row->save();
		$this->_db->query("ANALYZE TABLE `user_group`"); // after insert
		return 'ok';
	}
	
	private function isExistAdd()
	{
		$select = $this->_db->select()
				->from('user_group', array('id'))
				->where('group_name = ?', $this->_arrParam['groupname'], STRING)
				->limit(1);
		$result = $this->_db->fetchRow($select);
		return ( ! empty($result)) ? true : false;
	}
	
	public function listing()
	{
		$nbrows = $this->getAll($arrParam);
		
		$select = $this->_db->select()
				->from('user_group', array('id', 'group_name', 'status'))
				->order('group_name', 'ASC')
				->limit($this->_arrParam['limit'], $this->_arrParam['start']);
		$result = $this->_db->fetchAll($select);
		if ( ! empty($result))
		{
			foreach ($result as $row)
			{
				$arr[] = $row;
			}
			$jsonresult = json_encode($arr);
			return '({"total":"' .$nbrows. '","results":' .$jsonresult. '})';
		}
		else
		{
			return '({"total":"0", "results":""})';	
		}
	}
	
	private function getAll()
	{
		$select = $this->_db->select()
				->from('user_group', array('COUNT(id) as groups'));
		$result = $this->_db->fetchRow($select);
		return $result['groups'];
	}
	
	public function updatepres()
	{
		if ( ! empty($this->_arrParam))
		{
			if ($this->_arrParam['groupname'] == '')
			{
				return 'required';
			}
			
			if ($this->isExists())
			{
				return 'exist';
			}
			
			$where = 'id = ' . $this->_arrParam['id'];
			
			$row =  $this->fetchRow($where);
			$row->group_name = $this->_arrParam['groupname'];
			$row->status = ($this->_arrParam['id'] == 1) ? 1 : $this->_arrParam['status'];
			$row->save();
			
			// optimize table
			$this->_db->query("OPTIMIZE TABLE `user_group`");
			// delete cache ??? ko luu cache thanh vien nen ko can xoa
			return 'ok';
		}
	}
	
	private function isExists()
	{
		$select = $this->_db->select()
				->from('user_group', array('id'))
				->where('id != ?', $this->_arrParam['id'], INTEGER)
				->where('group_name = ?', $this->_arrParam['groupname'], STRING)
				->limit(1);
		$result = $this->_db->fetchRow($select);
		return ( ! empty($result)) ? true : false;
	}
	
	public function deletepres()
	{
		$idpres = stripslashes($this->_arrParam['ids']);
		$idpres = json_decode($idpres);
		if (sizeof($idpres) == 1)
		{				
			// khong duoc xoa nhom thanh vien co id la 1 (Administrator)
			if ($idpres[0] != 1)
			{
				$where = ' id = ' . $idpres[0];
				$this->delete($where);	
			}
			else
			{
				return 'no';	
			}
		} 
		else 
		{
			$id_array = array_keys($idpres, 1);
			if ( ! empty($id_array))
			{
				unset($idpres[$id_array[0]]);
			}
			$new_id = implode(',', $idpres);
			$where = 'id IN (' .$new_id. ')';
			$this->delete($where);
		}
		// optimeize tat ca cac table bi thay doi du lieu...
		$this->_db->query("OPTIMIZE TABLE `user_group`");
		return 'ok';
	}
	
	public function getprivilege()
	{
		$group = $this->_arrParam['id'];
		if ($group)
		{
			$select = $this->_db->select()
					->from('privileges as p', array('controller', 'action'))
					->joinLeft('user_group_privileges as ugp', 'ugp.privilege_id = p.id AND ugp.group_id = ' . $group, array('status'));
			$result = $this->_db->fetchAll($select);
			
			if ( ! empty($result))
			{
				$data = array();
				$data['success'] = true;
				$data['data'] = array();
				foreach ($result as $privilege)
				{
					$data['data'][$privilege['controller'] . '_' . $privilege['action']] = ($privilege['status']) ? 1 : 0;
				}
				$data['data']['FieldID'] = $group;
				$data['data']['task'] = 'updatePrivilege';
				$data = json_encode($data);
				return $data;
			}
		}
	}
	
	public function updateprivilege()
	{
		$group = $group = $this->_arrParam['FieldID'];
		
		// kiem tra xem co duoc quyen cap quyen ko?
		if ($this->isAddPrivilege())
		{
			// disable all privilege first
			$this->_db->query("UPDATE `user_group_privileges` SET `status` = 0 WHERE `group_id` = " . $group);
			
			foreach ($this->_arrParam as $key => $privilege)
			{
				if ( ! in_array($key, array('updateprivilege', 'FieldID')))
				{
					$data = explode('_', $key);
					$controller = $data[0] ? $data[0] : false;
					$action = $data[1] ? $data[1] : false;
					
					if ($controller AND $action)
					{
						$privilege_id = $this->getPrivilegeID($controller, $action);
						if (false !== $privilege_id)
						{
							// check privilege first
							if ($this->isAdded($privilege_id, $group))
							{
								// da them roi thi update
								$this->_db->query("UPDATE `user_group_privileges` SET `status` = 1 WHERE `group_id` = " .$group. " AND `privilege_id` = " .$privilege_id. " LIMIT 1");
							}
							else
							{
								$this->_db->query("INSERT INTO `user_group_privileges` VALUES ('', '" .$privilege_id. "', '" .$group. "', 1)");
							}
							
							// moi lan update hay insert thi xoa cache privilege
							$cache = new Zendvn_Cache();
							$cache->remove('privileges_' . $group);
						}
					}
					else
					{
						return "{success:true, data:'false'}";
					}
				}
			}
			return "{success:true, data:'ok'}";
		}
		else
		{
			return "{success:true, data:'privilege'}";	
		}
	}
	
	private function isAddPrivilege()
	{
		$ns = new Zend_Session_Namespace('info');
		$ns = $ns->getIterator();
		$group = $ns['member']['group_id'];
		if ($group == 1)
		{
			return true;	
		}
		
		$select = $this->_db->select()
				->from('user_group_privileges', array('id'))
				->where('group_id = ?', $group, INTEGER)
				->where('privilege_id = 11')
				->where('status = 1')
				->limit(1);
		$result = $this->_db->fetchRow($select);
		return ( ! empty($result)) ? true : false;
	}
	
	private function getPrivilegeID($controller, $action)
	{
		$select = $this->_db->select()
				->from('privileges', array('id'))
				->where('controller = ?', $controller, STRING)
				->where('action = ?', $action, STRING)
				->limit(1);
		$result = $this->_db->fetchRow($select);
		return ( ! empty($result)) ? $result['id'] : false;
	}
	
	private function isAdded($privilege_id, $group)
	{
		$select = $this->_db->select()
				->from('user_group_privileges', array('id'))
				->where('privilege_id = ?', $privilege_id, INTEGER)
				->where('group_id = ?', $group, INTEGER)
				->limit(1);
		$result = $this->_db->fetchRow($select);
		return ( ! empty($result)) ? true : false;
	}
}